﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CRMBiz.CalculateInterest
{
    public static class SACC
    {
        public static DataTable SACCCalculateByTerm(double loanAmount, int term, int repaymentOpt, double establishFee, double totMonthlyFee, DateTime settlementDate, DateTime firstPaymentDate)
        {
            DataTable dtSchedule = new DataTable();

            double totCharges = establishFee + totMonthlyFee;
            double totLoanAmount = (loanAmount + totCharges);
            double instalmentAmt = (totLoanAmount / term);

            dtSchedule.Columns.Add("DueDate", typeof(DateTime));
            dtSchedule.Columns.Add("Repayment", typeof(decimal));
            dtSchedule.Columns.Add("Balance", typeof(decimal));

            double balanceAmt = totLoanAmount;
            for (int cntr = 0; cntr < term; cntr++)
            {
                balanceAmt = balanceAmt - instalmentAmt;
                DataRow dr = dtSchedule.NewRow();
                dr["DueDate"] = firstPaymentDate.AddDays(cntr * repaymentOpt);
                dr["Repayment"] = Math.Round(instalmentAmt, 2);
                dr["Balance"] = Math.Round(balanceAmt, 2);

                dtSchedule.Rows.Add(dr);
            }

            return dtSchedule;
        }

        public static double GetTotalEstablishmentFee(double loanAmount, double establishFeePC)
        {
            return Math.Round(loanAmount * (establishFeePC / 100), 2);
        }

        public static double GetTotalMonthlyFee(double loanAmount, int term, int repaymentOpt, double monthlyFeePC, DateTime settlementDate, DateTime firstPaymentDate)
        {
            double monthlyFee = Math.Round((loanAmount * (monthlyFeePC / 100)), 2);

            DateTime lastPayDate = firstPaymentDate.AddDays((term - 1) * repaymentOpt);
            DateTime tempDecider = settlementDate;

            int mnthTimes = 0;

            while (tempDecider < lastPayDate)
            {
                mnthTimes = mnthTimes + 1;
                tempDecider = tempDecider.AddMonths(1);
            }

            return monthlyFee * mnthTimes;
        }
    }
}
